import React from 'react';
import ProTable from '@ant-design/pro-table';
import type { ProColumns, ActionType } from '@ant-design/pro-table';
// 搜索 表头
import { columnsData, columnsDataType, ModelType } from './data';
// 模拟的数据
import tableData from '../../mock/tableData';
import { Modal, Button, Form, Input, Select, message } from 'antd';
import { FormDesign } from 'bsin-workflow-ui';
import { CloseOutlined, PlusOutlined } from '@ant-design/icons';
import {
  saveFormModel,
  getPageListFromModel,
  saveForm,
} from '../../services/formManagement';

const { TextArea } = Input;

const FormManagement = () => {
  // 新增表单
  const [addForm] = Form.useForm();
  // table 绑定
  const tableRef = React.useRef<ActionType>();
  const genRef = React.useRef(); // class组件用 React.createRef()

  const [show, setShow] = React.useState(false);
  const [schema, setSchema] = React.useState('');
  // 控制新增模态框
  const [isAddInfoModalVisible, setIsAddInfoModalVisible] =
    React.useState(false);
  // 新增模态框确认按钮loading状态
  const [addOkLoading, setAddOkLoading] = React.useState<boolean>(false);
  // 在编辑的表格项
  const [settingItem, setSettingItem] = React.useState();

  // 表头数据
  const columns: ProColumns<columnsDataType>[] = columnsData;

  // 设计按钮
  const design = (record: any) => {
    setSchema(JSON.parse(record.modelEditorJson));
    setSettingItem(record);
    setShow(true);
  };

  // 操作行数据 自定义操作行
  const actionRender: any = (text: any, record: any, index: number) => (
    <ul className="ant-list-item-action" style={{ margin: 0 }}>
      <li>
        <a onClick={() => design(record)}>设计</a>
        <em className="ant-list-item-action-split"></em>
      </li>
      <li>
        <a onClick={() => {}}>删除</a>
      </li>
    </ul>
  );

  // 自定义数据的表格头部数据
  columns.forEach((item: any) => {
    item.dataIndex === 'action' ? (item.render = actionRender) : undefined;
  });
  // 打开新增模态框
  const addInfo = () => {
    setIsAddInfoModalVisible(true);
  };

  // 新增模态框确定
  const addModeOk = async () => {
    setAddOkLoading(true);
    let addFormData = addForm.getFieldsValue();
    // if (!modelTypeId) {
    //   message.error('请选择模型类型');
    //   setAddOkLoading(false);
    //   return;
    // }
    let res = await saveFormModel({ ...addFormData, modelType: 2 });
    if (res.code == '000000') {
      message.success('添加成功');
      tableRef.current?.reload();
      addForm.resetFields();
    } else {
      message.error('添加失败');
    }
    setAddOkLoading(false);
    setIsAddInfoModalVisible(false);
  };

  // 新增模态框取消
  const addModeCancel = () => {
    addForm.resetFields();
    setIsAddInfoModalVisible(false);
  };

  // 保存表单
  const saveFormSchema = async (schemas: any) => {
    let saveRepresentation = {
      reusable: false,
      newVersion: true,
      comment: '',
      formRepresentation: {
        id: settingItem.id,
        formDefinition: schemas,
      },
    };
    let res = await saveForm({ saveRepresentation });
    if (res.code == '000000') {
      message.success('保存成功');
    } else {
      message.error('保存失败');
    }
  };

  return (
    <div>
      {/* Pro表格 */}
      <ProTable<columnsDataType>
        actionRef={tableRef}
        headerTitle="模型管理"
        bordered
        // 表头
        columns={columns}
        // 请求获取的数据
        request={async (params) => {
          let res = await getPageListFromModel({
            ...params,
            pageNum: params.current,
          });
          if (res.code !== '000000') {
            message.error('获取模型管理表格信息失败');
          }
          const result = {
            data: res.data,
            total: res.pagination?.totalSize,
          };
          return result;
        }}
        rowKey="id"
        // 本地存储表格列的显示数据
        columnsState={{
          persistenceKey: 'pro-table-singe-demos',
          persistenceType: 'localStorage',
        }}
        // 搜索框配置
        search={{
          labelWidth: 'auto',
        }}
        // 搜索表单的配置
        form={{
          ignoreRules: false,
        }}
        pagination={{
          pageSize: 5,
        }}
        dateFormatter="string"
        //设置工具栏按钮及事件
        toolBarRender={() => [
          // 新增模板按钮
          <Button
            key="button"
            icon={<PlusOutlined />}
            type="primary"
            onClick={addInfo}
          >
            新增
          </Button>,
        ]}
      />
      {show ? (
        <div
          style={{
            width: '99vw',
            height: '100vh',
            position: 'fixed',
            top: 0,
            left: 0,
            backgroundColor: '#fff',
            zIndex: 999,
          }}
        >
          <CloseOutlined
            onClick={() => {
              tableRef.current?.reload();
              setShow(false);
            }}
            style={{
              fontSize: '18px',
              position: 'fixed',
              top: 25,
              right: 20,
              zIndex: 99999,
            }}
          />
          <FormDesign
            saveFormSchema={saveFormSchema}
            schema={schema}
            settingItem={settingItem}
          />
        </div>
      ) : null}
      {/* 增加模态框 */}
      <Modal
        centered
        width={700}
        title="新建"
        open={isAddInfoModalVisible}
        onOk={addModeOk}
        onCancel={addModeCancel}
        confirmLoading={addOkLoading}
      >
        <Form
          form={addForm}
          name="basic"
          labelCol={{ span: 5 }}
          wrapperCol={{ span: 16 }}
          autoComplete="off"
        >
          {/* <Form.Item
            label="分类"
            name="modelType"
            rules={[{ required: true, message: '请选择模型类型' }]}
          >
            <Select options={ModelType} />
          </Form.Item> */}
          <Form.Item
            label="名称"
            name="name"
            rules={[{ required: true, message: '请输入模型名称' }]}
          >
            <Input />
          </Form.Item>
          <Form.Item
            label="标识编码"
            name="key"
            rules={[{ required: true, message: '请输入模型唯一的编码' }]}
          >
            <Input />
          </Form.Item>
          <Form.Item label="描述" name="description">
            <TextArea rows={4} />
          </Form.Item>
        </Form>
      </Modal>
      {/* <Modal
        open={show}
        onCancel={toggle}
        onOk={handleOk}
        okText="保存"
        cancelText="关闭"
        width="90%"
        bodyStyle={{ height: '70vh' }}
      >
      </Modal> */}
    </div>
  );
};

export default FormManagement;
